package com.dayatang.product.webapp.jersey;

import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dayatang.product.domain.Count;
import com.dayatang.product.domain.RegisterCode;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.common.WebServiceBase;

@Path("/count-manage/{registerCode}")
@Component
@Scope("request")
public class CountManageJersey extends BaseAction {

	private static final long serialVersionUID = 5424657730321383407L;

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String countManage(@PathParam("registerCode") String registerCode) {
		RegisterCode code = RegisterCode.getRegisterCodeByCode(registerCode);
		if (code != null) {
			Count count = new Count();
			count.setUseDate(new Date());
			String ipStr = getRequestIP();
			count.setIp(ipStr);
			count.setAddress(getIpAddress(ipStr));
			code.addCount(count);
			productApplication.saveEntity(code);
		}
		return OK;
	}
	
	private static String getIpAddress(String ip) {
		String url = "http://api.liqwei.com/location/?ip=" + ip;
		String ipResult = WebServiceBase.getWebServicesResult(url,null).getEntity(String.class);
		StringBuilder result = new StringBuilder();
		String[] results = ipResult.split("\\,");
		int i = 0;
		for (String str : results) {
			if (i == results.length - 1 && results.length > 2) {
				result.append("(").append(str).append(")");
			} else if (i > 0) {
				result.append(str);
			} 
			i++;
		}
		return result.toString();
	}
	
}
